package com.example.service;



import com.example.model.Person;
import com.example.model.Team;
import com.example.repository.PersonRepository;
import com.example.repository.TeamRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; // 确保使用的是Spring的Transactional

@Service
public class PersonService {

    private final PersonRepository personRepository;
    private final TeamRepository teamRepository;

    @Autowired
    public PersonService(PersonRepository personRepository, TeamRepository teamRepository) {
        this.personRepository = personRepository;
        this.teamRepository = teamRepository;
    }

    @Transactional
    public void addPersonToTeam(Long personId, Long teamId) {
        Person person = personRepository.findById(personId).orElseThrow(() -> new RuntimeException("Person not found"));
        Team team = teamRepository.findById(teamId).orElseThrow(() -> new RuntimeException("Team not found"));

        // 双向关联
        team.getMembers().add(person);
        person.getTeams().add(team);

        // 保存更新
        personRepository.save(person);
        teamRepository.save(team);
    }
}
